package com.fangmou.ing.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created : 11-10-12 上午11:02
 * By      : liming
 */
public class FreemarkerExpressionCompute implements ExpressionCompute {

    /**
     * 计算逻辑表达式
     *
     * @param innerVer 内嵌的变量名
     * @param express  表达式语句
     * @return
     * @object object 内嵌的变量
     */
    public boolean logicCompute(Object object, String innerVer, String express) {
        String ftl = "<#if " + express + ">true<#else>false</#if>";

        Template temp ;
        Configuration cfg = new Configuration();
        try {
            temp = new Template("logicExpression", new StringReader(ftl), cfg);
        } catch (IOException e) {
            throw new RuntimeException("计算表达式[" + express + "]失败，",e);
        }
        Map root = new HashMap();
        root.put(innerVer, object);
        StringWriter sw = new StringWriter();
        try {
            temp.process(root, sw);
        } catch (TemplateException e) {
            throw new RuntimeException("表达式模版[" + ftl + "]解析失败，",e);
        } catch (IOException e) {
            throw new RuntimeException("计算表达式[" + express + "]失败，",e);
        }
        String result = sw.toString();
        if("true".equals(result))
            return true;
        else if("false".equals(result))
            return false;
        else
            throw new RuntimeException("表达式[" + express + "]的计算结果[" + result + "]非法");
    }
}
